/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.clusterresultstrangertrack.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.hontu.issued.util.HT_DEVICE_POST;
import vip.xiaonuo.hontu.issued.util.HongTuRequestUrl;
import vip.xiaonuo.modular.clusterresultstrangertrack.entity.ClusterResultStrangerTrack;
import vip.xiaonuo.modular.clusterresultstrangertrack.enums.ClusterResultStrangerTrackExceptionEnum;
import vip.xiaonuo.modular.clusterresultstrangertrack.mapper.ClusterResultStrangerTrackMapper;
import vip.xiaonuo.modular.clusterresultstrangertrack.param.ClusterResultStrangerTrackParam;
import vip.xiaonuo.modular.clusterresultstrangertrack.param.StrangerTrackQuery;
import vip.xiaonuo.modular.clusterresultstrangertrack.param.StrangerTrackResponse;
import vip.xiaonuo.modular.clusterresultstrangertrack.service.ClusterResultStrangerTrackService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.clustertaskresult.entity.ClusterTaskResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 高频陌生人轨迹service接口实现类
 *
 * @author Joe
 * @date 2023-07-05 15:37:26
 */
@Service
public class ClusterResultStrangerTrackServiceImpl extends ServiceImpl<ClusterResultStrangerTrackMapper, ClusterResultStrangerTrack> implements ClusterResultStrangerTrackService {

    private final String redis_key = "STRANGER_RESULT:";

    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private RedissonClient client;

    @Override
    public PageResult<ClusterResultStrangerTrack> page(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        QueryWrapper<ClusterResultStrangerTrack> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(clusterResultStrangerTrackParam)) {
            if(ObjectUtil.isNotEmpty(clusterResultStrangerTrackParam.getTaskResultId())){
                queryWrapper.lambda().eq(ClusterResultStrangerTrack::getTaskResultId, clusterResultStrangerTrackParam.getTaskResultId());
            }

            queryWrapper.lambda().orderByDesc(ClusterResultStrangerTrack :: getTimestamp);
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<ClusterResultStrangerTrack> list(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        return this.list();
    }

    @Override
    public void add(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        ClusterResultStrangerTrack clusterResultStrangerTrack = new ClusterResultStrangerTrack();
        BeanUtil.copyProperties(clusterResultStrangerTrackParam, clusterResultStrangerTrack);
        this.save(clusterResultStrangerTrack);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        this.removeById(clusterResultStrangerTrackParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        ClusterResultStrangerTrack clusterResultStrangerTrack = this.queryClusterResultStrangerTrack(clusterResultStrangerTrackParam);
        BeanUtil.copyProperties(clusterResultStrangerTrackParam, clusterResultStrangerTrack);
        this.updateById(clusterResultStrangerTrack);
    }

    @Override
    public ClusterResultStrangerTrack detail(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        return this.queryClusterResultStrangerTrack(clusterResultStrangerTrackParam);
    }

    @Override
    public void syncStrangerTrack(ClusterTaskResult result) {
        // 根据聚类结果获取设备
        DeviceBase device = deviceBaseService.getById(result.getDeviceId());

        if(ObjectUtil.isNull(device)){
            throw new ServiceException(500,"设备不存在");
        }
        if(ObjectUtil.notEqual( device.getDeviceState(),"1")){
            throw new ServiceException(500,"设备不在线");
        }

        // 获取Redis中记录的上次查询时间
        String key = redis_key + result.getProfileId();
        RBucket<Long> bucket = client.getBucket(key);
        // 查询过去10分钟的数据
        if(!bucket.isExists()){
            // 防止数据过多，只查询过去10分钟的数据
            bucket.set(System.currentTimeMillis() - 10 * 60 * 1000);
//            bucket.set(1672502400 * 1000L);// 2023-01-01 00:00:00
        }
        Long now = new Date().getTime();

        StrangerTrackQuery query = new StrangerTrackQuery(result.getProfileId(), bucket.get(),now);
        List<ClusterResultStrangerTrackParam> tracks = new ArrayList<>();
        try {
            while(true){
                StrangerTrackResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_STRANGER_TRACK_QUERY , device.getCabinetIp(),device.getCabinetPort(),query , StrangerTrackResponse.class);
                if(response.getCode() == 0){ // 请求成功
                    if(response.getData().getList().isEmpty()){
                        break;
                    }
                    tracks.addAll(response.getData().getList());
                    query.addPageNum();
                    Thread.sleep(500);
                }else{
                    throw new ServiceException(response.getCode(),response.getMsg());
                }
            }
            for(ClusterResultStrangerTrackParam track : tracks){
                List<ClusterResultStrangerTrack> list = this.list(new LambdaQueryWrapper<ClusterResultStrangerTrack>()
                        .eq(ClusterResultStrangerTrack :: getTaskResultId , track.getTaskResultId())
                        .eq(ClusterResultStrangerTrack :: getTimestamp , track.getTimestamp()));
                if(!list.isEmpty()){
                    continue;
                }
                track.setTaskResultId(result.getId());
                track.setPushFlag(Boolean.FALSE);
                this.add(track);
            }
            bucket.set(now);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取高频陌生人轨迹
     *
     * @author Joe
     * @date 2023-07-05 15:37:26
     */
    private ClusterResultStrangerTrack queryClusterResultStrangerTrack(ClusterResultStrangerTrackParam clusterResultStrangerTrackParam) {
        ClusterResultStrangerTrack clusterResultStrangerTrack = this.getById(clusterResultStrangerTrackParam.getId());
        if (ObjectUtil.isNull(clusterResultStrangerTrack)) {
            throw new ServiceException(ClusterResultStrangerTrackExceptionEnum.NOT_EXIST);
        }
        return clusterResultStrangerTrack;
    }
}
